﻿using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Loger;
using Learun.Util.SqlSugar;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Learun.Application.Web
{
    /// <summary>
    /// 过滤器记录接口调用日志
    /// </summary>
    public class LogActionFilter : ActionFilterAttribute
    {
        static Log _logger = LogFactory.GetLogger("Info");
        private const string Key = "__action_duration__";
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
            var actionName = actionContext.ActionDescriptor.ActionName;
            var fullAction = $"{controllerName}/{actionName}";
            var x2 = actionContext.Request.Content;
            if (x2.Headers?.ContentType?.MediaType == "multipart/form-data")
            {
                _logger.Info($"{DateTime.Now}--{fullAction},{JsonConvert.SerializeObject(actionContext.ActionArguments)}\n");
            }
            else
            {
                _logger.Info($"{DateTime.Now}--{fullAction},{JsonConvert.SerializeObject(actionContext.ActionArguments)}, {actionContext.Request.Content.ReadAsStringAsync().Result}\n");
            }
            var action = SqlSugarHelper.Db.Queryable<ec_ActionEntity>().First(x => x.ControllerName == controllerName && x.ActionName == actionName);
            if (action == null)
            {
                action = new ec_ActionEntity()
                {
                    ControllerName = controllerName,
                    ActionName = actionName,
                    Count = 1
                };
                action.Create();
                SqlSugarHelper.Db.Insertable(action).ExecuteCommand();
            }
            else
            {
                action.Count += 1;
                action.Modify(action.ActionID);
                SqlSugarHelper.Db.Updateable(action).ExecuteCommand();
            }

            var stopWatch = new Stopwatch();
            actionContext.Request.Properties[Key] = stopWatch;
            stopWatch.Start();
            base.OnActionExecuting(actionContext);
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            if (!actionExecutedContext.Request.Properties.ContainsKey(Key))
            {
                return;
            }
            var stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
            if (stopWatch == null)
            {
                return;
            }
            stopWatch.Stop();
            var actionDescriptor = actionExecutedContext.ActionContext.ActionDescriptor;
            var actionName = actionDescriptor.ActionName;
            var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
            if (actionExecutedContext.Response != null)
            {
                _logger.Info(controllerName + "-" + actionName + " 运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                var action = SqlSugarHelper.Db.Queryable<ec_ActionEntity>().First(x => x.ControllerName == controllerName && x.ActionName == actionName);
                action.MeanTime = (action.MeanTime * (action.Count - 1) + stopWatch.ElapsedMilliseconds / 1000) / action.Count;
                action.Modify(action.ActionID);
                SqlSugarHelper.Db.Updateable(action).ExecuteCommand();
                //actionExecutedContext.Response.Content.Headers.Add("TotalSpendTimes", stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture));
            }
        }
    }
}